package com.mathpractise.controller;

import com.mathpractise.dto.response.StatisticsReportDTO;
import com.mathpractise.model.TrainingSession;
import com.mathpractise.service.StatisticsService;
import com.mathpractise.service.TrainingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 统计控制器
 */
@RestController
@RequestMapping("/api/statistics")
public class StatisticsController {
    
    private static final Logger logger = LoggerFactory.getLogger(StatisticsController.class);
    
    @Autowired
    private StatisticsService statisticsService;
    
    @Autowired
    private TrainingService trainingService;
    
    /**
     * 查询所有会话统计信息接口
     *
     * @return 统计报告列表
     */
    @GetMapping("/sessions")
    public ResponseEntity<ApiResponse<List<StatisticsReportDTO>>> getAllSessions() {
        logger.info("获取所有会话统计信息请求");
        // 获取所有会话
        List<TrainingSession> sessions = trainingService.getAllSessions();
        
        // 转换为统计报告列表
        List<StatisticsReportDTO> reports = new ArrayList<>();
        for (TrainingSession session : sessions) {
            StatisticsReportDTO report = statisticsService.getSessionStatistics(session.getSessionId());
            reports.add(report);
        }
        logger.info("成功获取 {} 个会话的统计信息", reports.size());
        
        return ResponseEntity.ok(ApiResponse.success(reports));
    }
    
    /**
     * 查询会话统计接口
     *
     * @param sessionId 会话ID
     * @return 统计报告
     */
    @GetMapping("/session/{sessionId}")
    public ResponseEntity<ApiResponse<StatisticsReportDTO>> getSessionStatistics(@PathVariable String sessionId) {
        logger.info("获取会话统计信息请求: sessionId={}", sessionId);
        StatisticsReportDTO report = statisticsService.getSessionStatistics(sessionId);
        logger.info("成功获取会话统计信息: sessionId={}", sessionId);
        return ResponseEntity.ok(ApiResponse.success(report));
    }
    
    /**
     * 导出会话统计数据为CSV格式
     *
     * @param sessionId 会话ID
     * @return CSV格式的数据
     */
    @GetMapping("/session/{sessionId}/export")
    public ResponseEntity<ApiResponse<String>> exportToCsv(@PathVariable String sessionId) {
        logger.info("导出CSV数据请求: sessionId={}", sessionId);
        String csvData = statisticsService.exportToCsv(sessionId);
        logger.info("成功导出CSV数据: sessionId={}", sessionId);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=statistics_" + sessionId + ".csv");
        headers.add(HttpHeaders.CONTENT_TYPE, "text/csv; charset=utf-8");
        return ResponseEntity.ok().headers(headers).body(ApiResponse.success(csvData));
    }
    
    /**
     * 删除指定日期之前的历史统计数据接口
     *
     * @param beforeDate 指定日期
     * @return 删除结果
     */
    @DeleteMapping("/history")
    public ResponseEntity<ApiResponse<String>> deleteHistoryStatistics(@RequestParam String beforeDate) {
        logger.info("删除历史统计数据请求: beforeDate={}", beforeDate);
        String result = statisticsService.deleteHistoryStatistics(beforeDate);
        logger.info("成功删除历史统计数据: beforeDate={}", beforeDate);
        return ResponseEntity.ok(ApiResponse.success(result));
    }
}